import { provide, reactive, getCurrentInstance, } from 'vue';
import { debounce } from '../utils';
// uniapp 不存在 isVNode 等：https://github.com/dcloudio/uni-app/issues/3386
// $children 拿到的是 ref，DropdownItem 存在 expose，即为 expose
// 需要防抖函数，否则 exposeProxy 会出现 null
export const sortChildren = debounce((parent, publicChildren, internalChildren) => {
    const vnodes = parent.proxy.$children;
    internalChildren.sort((a, b) => vnodes.indexOf(a.exposeProxy) - vnodes.indexOf(b.exposeProxy));
    const orderedPublicChildren = internalChildren.map((item) => item.proxy);
    publicChildren.sort((a, b) => {
        const indexA = orderedPublicChildren.indexOf(a);
        const indexB = orderedPublicChildren.indexOf(b);
        return indexA - indexB;
    });
}, 1000 / 60);
export function useChildren(key) {
    const publicChildren = reactive([]);
    const internalChildren = reactive([]);
    const parent = getCurrentInstance();
    const linkChildren = (value) => {
        const link = (child) => {
            if (child.proxy) {
                internalChildren.push(child);
                publicChildren.push(child.proxy);
                sortChildren(parent, publicChildren, internalChildren);
            }
        };
        const unlink = (child) => {
            const index = internalChildren.indexOf(child);
            publicChildren.splice(index, 1);
            internalChildren.splice(index, 1);
        };
        provide(key, Object.assign({
            link,
            unlink,
            children: publicChildren,
            internalChildren,
        }, value));
    };
    return {
        children: publicChildren,
        linkChildren,
    };
}
